#!/bin/bash

####################
## 主机初始化脚本 ##
####################

# 设置时区
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# 系统更新
#yum -y update 

# 同步时间
yum -y install ntpdate && ntpdate pool.ntp.org 
echo "1 1 * * * /usr/sbin/ntpdate pool.ntp.org" >> /var/spool/cron/root

# 设置本地Docker镜像私有仓库解析
echo -e  "请输入本地Docker镜像私有库IP"
read  REGISTRY_HOST

tmp=`cat /etc/hosts | grep registry.docker.hc  | wc -l`
if [[ $tmp > 0 ]]; then
	sed -i 's/.* registry.docker.hc/${STORAGE_HOST} registry.docker.hc /' /etc/hosts
else
	echo ${STORAGE_HOST} registry.docker.hc >> /etc/hosts
fi

tmp=`cat /etc/hosts | grep nfs.docker.hc  | wc -l`
if [[ $tmp > 0 ]]; then
	sed -i 's/.* nfs.docker.hc/${STORAGE_HOST} nfs.docker.hc /' /etc/hosts
else
	echo ${STORAGE_HOST} nfs.docker.hc >> /etc/hosts
fi

# 禁用SELINUX
setenforce 0
sed -i 's/SELINUX=.*/SELINUX=disabled/' /etc/selinux/config

# 禁用防火墙
systemctl stop firewalld.service
systemctl disable firewalld.service

# 安装Docker
yum remove -y docker \
                  docker-common \
                  docker-selinux \
                  docker-engine
#docker所依赖的包环境，为了方便不报错，推荐执行
yum install -y yum-utils device-mapper-persistent-data lvm2

#更新一下yum软件包的索引
yum makecache fast

# 安装containerd
yum install -y https://download.docker.com/linux/fedora/30/x86_64/stable/Packages/containerd.io-1.2.6-3.3.fc30.x86_64.rpm

# 配置docker源
sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
    
#阿里云源加速
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

sudo yum install docker-ce-3:19.03.8-3.el7

# Docker配置                                       
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://45p7qdl5.mirror.aliyuncs.com"],
  "insecure-registries":["registry.docker.hc:5000"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

systemctl enable docker
systemctl daemon-reload
systemctl restart docker

# 安装NFS
yum install -y nfs-utils

yum install -y system-storage-manager container-storage-setup

# 设置定时清理脚本
sudo mkdir -p /hc/script/
sudo tee /hc/script/clear.sh <<-'EOF'
#!/bin/bash
#删除所有<none>镜像
docker rmi $(docker images -f "dangling=true" -q)
EOF
chmod +x /hc/script/clear.sh
echo "2 1 * * * sh /hc/script/clear.sh" >> /var/spool/cron/root

# 安装GIT
yum install -y git
yum install -y unzip
yum install -y vim

mkdir -p /hc/data/
chmod -R 777 /hc/data

# TODO 时区设置失败
# TODO 安装完成校验
# TODO 定期清理日志 镜像